//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package test;

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class VolunteerService {
    private JFrame volunteerFrame;
    private DefaultTableModel volunteerModel;
    private JTable volunteerTable;
    private int currentUserId = 1;

    public VolunteerService() {
        this.initializeDatabase();
        this.volunteerFrame = new JFrame("志愿者服务");
        this.volunteerFrame.setSize(800, 600);
        this.volunteerFrame.setLocationRelativeTo((Component)null);
        String[] columns = new String[]{"活动名称", "活动时间", "需求人数", "已报名", "我的积分"};
        this.volunteerModel = new DefaultTableModel(columns, 0) {
            public boolean isCellEditable(int row, int column) {
                return column == 4;
            }
        };
        this.volunteerTable = new JTable(this.volunteerModel);
        this.loadActivitiesFromDatabase();
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton joinBtn = new JButton("报名参加");
        JButton certBtn = new JButton("生成证书");
        JButton backBtn = new JButton("返回主菜单");
        Font btnFont = new Font("SimSun", 0, 14);
        joinBtn.setFont(btnFont);
        certBtn.setFont(btnFont);
        backBtn.setFont(btnFont);
        joinBtn.addActionListener((e) -> this.registerForActivity());
        certBtn.addActionListener((e) -> this.generateCertificate());
        backBtn.addActionListener((e) -> {
            this.volunteerFrame.dispose();
            (new Menu(null)).setVisible(true);
        });
        buttonPanel.add(joinBtn);
        buttonPanel.add(certBtn);
        buttonPanel.add(backBtn);
        this.volunteerFrame.add(new JScrollPane(this.volunteerTable), "Center");
        this.volunteerFrame.add(buttonPanel, "South");
    }

    private void initializeDatabase() {
        String[] createTables = new String[]{"CREATE TABLE IF NOT EXISTS volunteer_activities (id INT AUTO_INCREMENT PRIMARY KEY,activity_name VARCHAR(255) NOT NULL,activity_time VARCHAR(100) NOT NULL,required_count INT NOT NULL,registered_count INT DEFAULT 0,points_per_participation INT DEFAULT 10,description TEXT)", "CREATE TABLE IF NOT EXISTS volunteer_participation (id INT AUTO_INCREMENT PRIMARY KEY,user_id INT NOT NULL,activity_id INT NOT NULL,participation_date DATETIME NOT NULL,points_earned INT NOT NULL,FOREIGN KEY (activity_id) REFERENCES volunteer_activities(id))"};

        try (
                Connection conn = this.getConnection();
                Statement stmt = conn.createStatement();
        ) {
            for(String sql : createTables) {
                stmt.execute(sql);
            }

            if (this.isTableEmpty("volunteer_activities")) {
                String[] sampleActivities = new String[]{"INSERT INTO volunteer_activities (activity_name, activity_time, required_count, description) VALUES ('关爱孤寡老人', '每周周六上午', 10, '为社区孤寡老人提供陪伴和帮助')", "INSERT INTO volunteer_activities (activity_name, activity_time, required_count, description) VALUES ('社区环境清理', '每月第一个周日', 20, '参与社区公共区域的清洁工作')"};

                for(String insertSql : sampleActivities) {
                    stmt.execute(insertSql);
                }
            }
        } catch (SQLException e) {
            this.showErrorDialog("数据库初始化失败", e);
        }

    }

    private boolean isTableEmpty(String tableName) throws SQLException {
        String sql = "SELECT COUNT(*) FROM " + tableName;

        boolean var6;
        try (
                Connection conn = this.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
        ) {
            var6 = rs.next() && rs.getInt(1) == 0;
        }

        return var6;
    }

    private void loadActivitiesFromDatabase() {
        String sql = "SELECT id, activity_name, activity_time, required_count, registered_count, points_per_participation FROM volunteer_activities";

        try (
                Connection conn = this.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
        ) {
            while(rs.next()) {
                int activityId = rs.getInt("id");
                String activityName = rs.getString("activity_name");
                String activityTime = rs.getString("activity_time");
                int requiredCount = rs.getInt("required_count");
                int registeredCount = rs.getInt("registered_count");
                int points = this.getPointsForUser(activityId);
                this.volunteerModel.addRow(new Object[]{activityName, activityTime, requiredCount, registeredCount, points});
            }
        } catch (SQLException e) {
            this.showErrorDialog("加载活动失败", e);
        }

    }

    private int getPointsForUser(int activityId) {
        String sql = "SELECT SUM(points_earned) FROM volunteer_participation WHERE user_id = ? AND activity_id = ?";

        try {
            int var6;
            try (
                    Connection conn = this.getConnection();
                    PreparedStatement pstmt = conn.prepareStatement(sql);
            ) {
                pstmt.setInt(1, this.currentUserId);
                pstmt.setInt(2, activityId);
                ResultSet rs = pstmt.executeQuery();
                var6 = rs.next() ? rs.getInt(1) : 0;
            }

            return var6;
        } catch (SQLException e) {
            this.showErrorDialog("查询积分失败", e);
            return 0;
        }
    }

    private void registerForActivity() {
        int selectedRow = this.volunteerTable.getSelectedRow();
        if (selectedRow >= 0) {
            String activityName = (String)this.volunteerModel.getValueAt(selectedRow, 0);
            int activityId = this.getActivityIdByName(activityName);
            if (activityId == -1) {
                this.showErrorDialog("错误", new Exception("找不到对应活动"));
                return;
            }

            int confirm = JOptionPane.showConfirmDialog(this.volunteerFrame, "确定要报名参加" + activityName + "吗?", "确认报名", 0);
            if (confirm == 0) {
                if (this.registerUserForActivity(activityId)) {
                    this.refreshActivityList();
                    JOptionPane.showMessageDialog(this.volunteerFrame, "报名成功!");
                } else {
                    JOptionPane.showMessageDialog(this.volunteerFrame, "报名失败!", "错误", 0);
                }
            }
        }

    }

    private int getActivityIdByName(String name) {
        String sql = "SELECT id FROM volunteer_activities WHERE activity_name = ?";

        try {
            int var6;
            try (
                    Connection conn = this.getConnection();
                    PreparedStatement pstmt = conn.prepareStatement(sql);
            ) {
                pstmt.setString(1, name);
                ResultSet rs = pstmt.executeQuery();
                var6 = rs.next() ? rs.getInt("id") : -1;
            }

            return var6;
        } catch (SQLException e) {
            this.showErrorDialog("查询活动ID失败", e);
            return -1;
        }
    }

    private boolean registerUserForActivity(int activityId) {
        String checkSql = "SELECT required_count, registered_count, points_per_participation FROM volunteer_activities WHERE id = ? FOR UPDATE";
        String updateSql = "UPDATE volunteer_activities SET registered_count = registered_count + 1 WHERE id = ?";
        String insertSql = "INSERT INTO volunteer_participation (user_id, activity_id, participation_date, points_earned) VALUES (?, ?, NOW(), ?)";
        Connection conn = null;

        boolean var43;
        try {
            conn = this.getConnection();
            conn.setAutoCommit(false);
            PreparedStatement pstmt = conn.prepareStatement(checkSql);

            label313: {
                label314: {
                    try {
                        pstmt.setInt(1, activityId);
                        ResultSet rs = pstmt.executeQuery();
                        if (!rs.next()) {
                            break label314;
                        }

                        int required = rs.getInt("required_count");
                        int registered = rs.getInt("registered_count");
                        int points = rs.getInt("points_per_participation");
                        if (registered >= required) {
                            JOptionPane.showMessageDialog(this.volunteerFrame, "该活动报名人数已满", "提示", 2);
                            var43 = false;
                            break label313;
                        }

                        PreparedStatement updateStmt = conn.prepareStatement(updateSql);

                        try {
                            updateStmt.setInt(1, activityId);
                            updateStmt.executeUpdate();
                        } catch (Throwable var36) {
                            if (updateStmt != null) {
                                try {
                                    updateStmt.close();
                                } catch (Throwable var34) {
                                    var36.addSuppressed(var34);
                                }
                            }

                            throw var36;
                        }

                        if (updateStmt != null) {
                            updateStmt.close();
                        }

                        updateStmt = conn.prepareStatement(insertSql);

                        try {
                            updateStmt.setInt(1, this.currentUserId);
                            updateStmt.setInt(2, activityId);
                            updateStmt.setInt(3, points);
                            updateStmt.executeUpdate();
                        } catch (Throwable var35) {
                            if (updateStmt != null) {
                                try {
                                    updateStmt.close();
                                } catch (Throwable var33) {
                                    var35.addSuppressed(var33);
                                }
                            }

                            throw var35;
                        }

                        if (updateStmt != null) {
                            updateStmt.close();
                        }

                        conn.commit();
                        var43 = true;
                    } catch (Throwable var37) {
                        if (pstmt != null) {
                            try {
                                pstmt.close();
                            } catch (Throwable var32) {
                                var37.addSuppressed(var32);
                            }
                        }

                        throw var37;
                    }

                    if (pstmt != null) {
                        pstmt.close();
                    }

                    return var43;
                }

                if (pstmt != null) {
                    pstmt.close();
                }

                return false;
            }

            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    this.showErrorDialog("回滚事务失败", ex);
                }
            }

            this.showErrorDialog("报名失败", e);
            boolean rs = false;
            return rs;
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    conn.close();
                } catch (SQLException e) {
                    this.showErrorDialog("关闭连接失败", e);
                }
            }

        }

        return var43;
    }

    private void generateCertificate() {
        String sql = "SELECT SUM(points_earned) FROM volunteer_participation WHERE user_id = ?";

        try (
                Connection conn = this.getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);
        ) {
            pstmt.setInt(1, this.currentUserId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                int totalPoints = rs.getInt(1);
                if (totalPoints > 0) {
                    JOptionPane.showMessageDialog(this.volunteerFrame, "您已获得" + totalPoints + "志愿者积分\n正在生成荣誉证书...");
                } else {
                    JOptionPane.showMessageDialog(this.volunteerFrame, "您尚未参与任何志愿者活动", "提示", 2);
                }
            }
        } catch (SQLException e) {
            this.showErrorDialog("计算积分失败", e);
        }

    }

    private void refreshActivityList() {
        this.volunteerModel.setRowCount(0);
        this.loadActivitiesFromDatabase();
    }

    private Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/community_db?" +
                "useSSL=false&" +
                "serverTimezone=UTC&" +
                "allowPublicKeyRetrieval=true";
        String user = "root";
        String password = "Ht20041228";
        return DriverManager.getConnection(url, user, password);
    }

    private void showErrorDialog(String title, Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(this.volunteerFrame, title + ": " + e.getMessage(), "错误", 0);
    }

    public void show() {
        this.volunteerFrame.setVisible(true);
    }
}
